<?php
namespace Plu\Library\Assets;

use Plu\Library\Services\ServiceBase,
    Phalcon\Tag;

/**
 * PLU版本的资源管理器
 */
class Manager extends ServiceBase {

    const key_of_resources_list = "config:html:resources:list";

    const TTL = 5 * 60;

    private $version_suffix = "";

    public function __construct($mode, $suffix = "") {
        if (empty($suffix)) {
            switch ($mode) {
            case 'test':
                $suffix = "";
                break;
            case 'stage':
                $suffix = "-rc";
                break;
            default:
                $suffix = "";
                break;
            }
        }

        $this->version_suffix = $suffix;
    }

    public function output($page, $version, $resource) {
        //拼接guid
        $resourceKey = $page.$version.$this->version_suffix.$resource;
        $guid = sprintf("rs_%s", md5($resourceKey));

        $path = $this->cache->get($guid);
        if (empty($path)) {
            $_redis = $this->getRedis('config');
            $path = $_redis->hGet(self::key_of_resources_list, $resourceKey);

            $this->cache->save($guid, $path, self::TTL);
        }

        return $path;
    }

    public function outputCss($page, $version, $resource) {
        $path = $this->output($page, $version, $resource);

        return Tag::stylesheetLink($path, false);
    }

    public function outputJs($page, $version, $resource) {
        $path = $this->output($page, $version, $resource);

        return Tag::javascriptInclude($path, false);
    }

    public function outputImage($page, $version, $resource) {
        $path = $this->output($page, $version, $resource);

        return Tag::image($path, false);
    }
}
